package com.hmkj.core.service.account.impl;

import com.hmkj.common.baseMapper.GenericMapper;
import com.hmkj.common.utils.DateUtils;
import com.hmkj.core.constant.Constant;
import com.hmkj.core.constant.Enum;
import com.hmkj.core.mapper.account.AccountLogMapper;
import com.hmkj.core.po.account.Account;
import com.hmkj.core.po.account.AccountLog;
import com.hmkj.core.po.order.Order;
import com.hmkj.core.service.account.AccountLogService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 资金记录业务相关Service接口实现<br>
 *
 * @author eproo
 * @ClassName: AccountLogServiceImpl
 * @date 2018-07-05 09:50:54
 */
@Service
@Scope("prototype")
@Transactional(rollbackFor = Exception.class)
public class AccountLogServiceImpl implements AccountLogService {

    @Resource
    private AccountLogMapper accountLogMapper;

    @Override
    public GenericMapper<AccountLog, Integer> _getMapper() {
        return accountLogMapper;
    }

    @Override
    public BigDecimal selectSumByType(AccountLog.TYPE t, AccountLog.TYPE t1, Integer userId) {
        Map<String, Object> param = new HashMap<>();
        param.put("whereSql", "(" + t.code + "," + t1.code + ") and user_id = " + userId);
        return accountLogMapper.selectSumByType(param);
    }

    @Override
    public BigDecimal selectSumByAirectionType(AccountLog.DIRECTION direction, AccountLog.TYPE type, Integer userId) {
        return accountLogMapper.selectSumByAirectionType(direction.code, type.code, userId);
    }

    @Override
    public BigDecimal selectSumAmountByType(AccountLog.TYPE type, String startTime, String endTime) {
        Map<String, Object> param = new HashMap<>();
        param.put("type", type.code);
        param.put("startTime", startTime);
        param.put("endTime", endTime);
        return accountLogMapper.selectSumAmountByType(param);
    }

    @Override
    public void generateLogForPlat(Order order, Account account, BigDecimal sellerFee, Enum.Direction direction, Constant.ACCOUNT_TYPE accountType) {
        accountLogMapper.insert(new AccountLog(a -> {
            a.setOrderId(order.getId());
            a.setUserId(1);
            a.setDirection((int) direction.getValue());
            a.setAmount(sellerFee);
            a.setTotal(account.getAvailable());
            a.setType(accountType.getValue());
            a.setDelFlag(AccountLog.DELFLAG.NORMAL.code);
            a.setCreateTime(DateUtils.getNow());
        }));
    }
}
